package com.it.system.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it.system.educommonapi.entity.User;
import com.it.system.user.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 实现自定义用户验证的逻辑类
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("UserDetailsServiceImpl 正在加载用户: {}", username);
        //使用用户名查询用户
        User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUsername,username));
        //如果用户为空
        if(user == null){
            log.error("UserDetailsServiceImpl 用户名不存在: {}", username);
            throw new UsernameNotFoundException("用户名不存在");
        }
        log.info("UserDetailsServiceImpl 成功加载用户: {}", username);
        //不需要权限
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("");
        org.springframework.security.core.userdetails.User userDetails =
                new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
        return userDetails;
    }
}
